// gmv2psd v1.00
// Written by Damian Grove

#include <stdio.h>
#include <stdlib.h>

FILE *in;
FILE *out;
int i;
int size;

int main(int argc, char *argv[]){
	// Check to see if command line used properly
	if(argc != 3){
		printf("USAGE: gmv2psd [in.gmv] [out.psd]\n");
		system("PAUSE");
		return 0;
	}
	
	// Open GMV file
	in = fopen(argv[1], "rb");
	
	// Get the size of the GMV file
	fseek(in, 0, SEEK_END);
	size = (ftell(in) - 0x40) / 3;
	rewind(in);
	
	// Verify the header info
	fread(&i, 4, 1, in);	// "Gens"
	if(i != 0x736E6547){
		fclose(in);
		printf("ERROR: Invalid GMV file!\n");
		system("PAUSE");
		return 0;
	}
	fread(&i, 4, 1, in);	// " Mov"
	if(i != 0x766F4D20){
		fclose(in);
		printf("ERROR: Invalid GMV file!\n");
		system("PAUSE");
		return 0;
	}
	fread(&i, 2, 1, in);	// "ie"
	if((i & 0xFFFF) != 0x6569){
		fclose(in);
		printf("ERROR: Invalid GMV file!\n");
		system("PAUSE");
		return 0;
	}
	
	// Create PSD file
	out = fopen(argv[2], "wb");
	
	// Write PSD header
	i = 0;
	fwrite(&i, 2, 1, out);
	fwrite(&size, 2, 1, out);
	fwrite(&i, 2, 1, out);
	
	// Convert demo data
	fseek(in, 0x40, SEEK_SET);
	while(size > 0){
		fread(&i, 3, 1, in);
		i ^= 0xFFFFFF;
		i = (i & 0x80) | ((i & 0x60) >> 1) | ((i & 0x10) << 2) | (i & 0xF);
		fwrite(&i, 1, 1, out);
		size--;
	}
	
	// Close files
	i = ftell(out);
	fclose(in);
	fclose(out);
	printf("GMV data successfully converted to PSD!\nBytes written: %i\n", i);
	system("PAUSE");
	
	return 0;
}
